package com.demarc.pesquisas.infraestrutura.util.relatorio;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.demarc.pesquisas.infraestrutura.excecao.InfraException;
import com.demarc.pesquisas.infraestrutura.web.jsf.AtributoSessaoConstants;

public class ReportServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// removing parameters from session
		String type = getContentType(request);
		String filename = getAttribute(AtributoSessaoConstants.FILE_NAME,
				request);
		byte[] content = getAttribute(AtributoSessaoConstants.CONTENT, request);

		// setting the content attributes
		setContentType(response, type);
		response.setHeader("Content-Disposition", "attachment;filename=\""
				+ filename + "\"");
		response.setContentLength(content.length);

		// writing the content to the response
		ServletOutputStream output = response.getOutputStream();
		try {
			output.write(content, 0, content.length);
			output.flush();
		} finally {
			output.close();
		}
	}

	private void setContentType(HttpServletResponse response, String type) {
		if ("pdf".equalsIgnoreCase(type)) {
			response.setContentType("application/pdf");
		} else if ("xls".equalsIgnoreCase(type)) {
			response.setContentType("application/xls");
		} else if ("doc".equalsIgnoreCase(type)) {
			response.setContentType("application/doc");
		} else {
			throw new InfraException("Type " + type + " not supported!");
		}
	}

	private String getContentType(HttpServletRequest request) {
		String type = request.getRequestURI();
		return type.substring(type.lastIndexOf('/') + 1, type.length());
	}

	@SuppressWarnings("unchecked")
	private <F> F getAttribute(String attribute, HttpServletRequest request) {
		HttpSession session = request.getSession();
		F content = (F) session.getAttribute(attribute);
		session.removeAttribute(attribute);

		if (content == null) {
			throw new InfraException("No \"" + attribute
					+ "\" found in session!");
		}
		return content;
	}
}